package com.itlong.cloud.property.service.impl;

import com.itlong.cloud.POJO.DTO.BaseDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateWeChatDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyWeChatDTO;
import com.itlong.cloud.POJO.PO.WeChatOfficialAuthInfoPO;
import com.itlong.cloud.POJO.VO.operate.OperateWeChatVO;
import com.itlong.cloud.POJO.VO.property.PropertyWeChatVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.property.dao.IPropertyWeChatDao;
import com.itlong.cloud.property.service.IPropertyWeChatService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      物业-微信支付相关服务接口实现类
 * </desc>
 *
 * @createDate 2019/09/09
 */
@Service
public class PropertyWeChatServiceImpl implements IPropertyWeChatService {

    @Autowired
    private IPropertyWeChatDao iPropertyWeChatDao;

    /**
     * <desc>
     *      获取用户授权的appId
     * </desc>
     *
     * @return 用户授权的appId
     * @author wangzhi
     * @createDate 2019/09/09
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<Map<String, Object>> getAppId(BaseDTO baseDTO) throws Exception {
        return iPropertyWeChatDao.getAppId(baseDTO);
    }

    /**
     * <desc>
     *      获取公众号列表
     * </desc>
     *
     * @return 公众号列表
     * @author wangzhi
     * @createDate 2019/10/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<PropertyWeChatVO> getAppIdPage(BaseDTO baseDTO) throws Exception {
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(baseDTO);
        Page<PropertyWeChatVO> page = new Page<>();
        page.getPage().setPageSize(baseDTO.getPageSize());
        page.getPage().setCurrentPage(baseDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<PropertyWeChatVO> propertyWeChatVOS = iPropertyWeChatDao.getAppIdPage(params);
        page.setRows(propertyWeChatVOS, iPropertyWeChatDao.getAppIdRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      查看用户授权
     * </desc>
     *
     * @return 用户授权信息
     * @author wangzhi
     * @createDate 2019/10/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public PropertyWeChatVO getOneAppId(PropertyWeChatDTO propertyWeChatDTO) throws Exception {
        return iPropertyWeChatDao.getOneAppId(propertyWeChatDTO);
    }

    /**
     * <desc>
     *      解除微信公众号绑定
     * </desc>
     *
     * @return 受影响行数
     * @author wangzhi
     * @createDate 2019/10/21
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer deleteAppIdBinding(PropertyWeChatDTO propertyWeChatDTO) throws Exception {
        return iPropertyWeChatDao.deleteAppIdBinding(propertyWeChatDTO);
    }

    /**
     * <desc>
     *      添加appId对应商户号
     * </desc>
     *
     * @return 受影响行数
     * @author wangzhi
     * @createDate 2019/09/10
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveMchId(PropertyWeChatDTO propertyWeChatDTO) throws Exception {
        WeChatOfficialAuthInfoPO checkProjectAuth = iPropertyWeChatDao.checkProjectAuth(propertyWeChatDTO);
        if (checkProjectAuth != null) {
            return -1;
        }
        String projectId = propertyWeChatDTO.getProjectId();
        propertyWeChatDTO.setProjectId(null);
        // 因授权信息可以绑定多个小区，先查询暂时还未添加过商户号即未绑定过小区的appId信息，如果有，则进行此条数据的修改，如果没有，则查询添加过的appId信息再在此条信息基础上进行添加
        WeChatOfficialAuthInfoPO oneWeChatAuthDetail = iPropertyWeChatDao.getOneWeChatAuthDetail(propertyWeChatDTO);
        if (oneWeChatAuthDetail == null) {
            // 添加操作
            WeChatOfficialAuthInfoPO weChatOfficialAuthInfoPO = new WeChatOfficialAuthInfoPO();
            propertyWeChatDTO.setProjectId(projectId);
            WeChatOfficialAuthInfoPO oneWeChatAuthPO = iPropertyWeChatDao.getOneWeChatAuthDetail(propertyWeChatDTO);
            BeanUtils.copyProperties(oneWeChatAuthPO, weChatOfficialAuthInfoPO);
            weChatOfficialAuthInfoPO.setInfoId(LogicIdUtil.bussinessId());
            weChatOfficialAuthInfoPO.setProjectId(projectId);
            weChatOfficialAuthInfoPO.setApiKey(propertyWeChatDTO.getApiKey());
            weChatOfficialAuthInfoPO.setMchId(propertyWeChatDTO.getMchId());
            weChatOfficialAuthInfoPO.setUpdateTime(new Date());
            weChatOfficialAuthInfoPO.setMchIdUpdateTime(new Date());
            Map<String,Object> map = SqlUtil.durableData(weChatOfficialAuthInfoPO,PlatformConstants.TABLE_SAVE);
            return iPropertyWeChatDao.save(map);
        } else {
            // 修改操作
            oneWeChatAuthDetail.setProjectId(projectId);
            oneWeChatAuthDetail.setApiKey(propertyWeChatDTO.getApiKey());
            oneWeChatAuthDetail.setMchId(propertyWeChatDTO.getMchId());
            oneWeChatAuthDetail.setUpdateTime(new Date());
            oneWeChatAuthDetail.setMchIdUpdateTime(new Date());
            Map<String,Object> map = SqlUtil.durableData(oneWeChatAuthDetail,PlatformConstants.TABLE_UPDATE);
            return iPropertyWeChatDao.update(map);
        }
    }

    /**
     * <desc>
     *      修改appId对应商户号
     * </desc>
     *
     * @return 受影响行数
     * @author wangzhi
     * @createDate 2019/10/22
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer updateMchId(PropertyWeChatDTO propertyWeChatDTO) throws Exception {
        return iPropertyWeChatDao.updateMchId(propertyWeChatDTO);
    }

    /**
     * <desc>
     *      分页查询appId和商户号信息
     * </desc>
     *
     * @return 分页数据信息
     * @author wangzhi
     * @createDate 2019/09/10
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<PropertyWeChatVO> getMchIdPage(PropertyWeChatDTO propertyWeChatDTO) throws Exception {
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(propertyWeChatDTO);
        Page<PropertyWeChatVO> page = new Page<>();
        page.getPage().setPageSize(propertyWeChatDTO.getPageSize());
        page.getPage().setCurrentPage(propertyWeChatDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<PropertyWeChatVO> propertyWeChatVOS = iPropertyWeChatDao.getMchIdPage(params);
        page.setRows(propertyWeChatVOS, iPropertyWeChatDao.getMchIdRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      解除商户号绑定
     * </desc>
     *
     * @return 受影响行数
     * @author wangzhi
     * @createDate 2019/10/22
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer deleteMchIdBinding(PropertyWeChatDTO propertyWeChatDTO) throws Exception {
        // 解除商户号绑定之前，判断该公众号数据条数，如果1条以上，则直接解除，如果只有一条，则先复制一条再解除，一切遵守的原则是被解除的数据作为记录保留，供运营查看
        // 先将此条记录查询出来（去除projectId，mchId，apiKey，mchIdUpdateTime），用于复制
        WeChatOfficialAuthInfoPO weChatOfficialAuthInfoPO = iPropertyWeChatDao.getOneForCopy(propertyWeChatDTO);
        // 解除绑定
        Integer row = iPropertyWeChatDao.deleteMchIdBinding(propertyWeChatDTO);
        if (row == 0) {
            return row;
        }
        propertyWeChatDTO.setLoginUserId(weChatOfficialAuthInfoPO.getPropertyUserId());
        propertyWeChatDTO.setAppId(weChatOfficialAuthInfoPO.getAppId());
        WeChatOfficialAuthInfoPO oneWeChatAuthDetail = iPropertyWeChatDao.getOneWeChatAuthDetail(propertyWeChatDTO);
        if (oneWeChatAuthDetail == null) {
            // 只有一条，解绑之后公众号信息没了，则复制一条添加
            weChatOfficialAuthInfoPO.setInfoId(LogicIdUtil.bussinessId());
            weChatOfficialAuthInfoPO.setUpdateTime(weChatOfficialAuthInfoPO.getCreateTime());
            Map<String,Object> map = SqlUtil.durableData(weChatOfficialAuthInfoPO,PlatformConstants.TABLE_SAVE);
            iPropertyWeChatDao.save(map);
        }
        return 1;
    }

    /**
     * <desc>
     *      保存微信公众号授权信息
     * </desc>
     *
     * @return 受影响行数
     * @author wangzhi
     * @createDate 2019/09/10
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveWeChatAuthInfoCallBack(WeChatOfficialAuthInfoPO weChatOfficialAuthInfoPO) throws Exception {
        /*// 如果之前已授权，数据库中存在数据，则进行更新，否则添加
        PropertyWeChatDTO propertyWeChatDTO = new PropertyWeChatDTO();
        propertyWeChatDTO.setLoginUserId(weChatOfficialAuthInfoPO.getPropertyUserId());
        propertyWeChatDTO.setAppId(weChatOfficialAuthInfoPO.getAppId());
        propertyWeChatDTO.setProjectId("111");
        WeChatOfficialAuthInfoPO oneWeChatAuthDetail = iPropertyWeChatDao.getOneWeChatAuthDetail(propertyWeChatDTO);
        if (oneWeChatAuthDetail == null) {
            // 不存在，添加操作
            weChatOfficialAuthInfoPO.setInfoId(LogicIdUtil.bussinessId());
            weChatOfficialAuthInfoPO.setAuthStatus(1);
            weChatOfficialAuthInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            weChatOfficialAuthInfoPO.setCreateTime(new Date());
            weChatOfficialAuthInfoPO.setUpdateTime(weChatOfficialAuthInfoPO.getCreateTime());
            Map<String,Object> map = SqlUtil.durableData(weChatOfficialAuthInfoPO,PlatformConstants.TABLE_SAVE);
            return iPropertyWeChatDao.save(map);
        } else {
            // 存在，修改操作，修改公众号主体名称、公众号昵称、授权原始信息、公众号类型、认证类型、创建时间(作为授权时间的依据)，且将原支付设置信息去除
            // 但在此之前，如果原来公众号绑定了多个项目，这次更新之后就会出现多条相同的公众号数据，故只留一条
            iPropertyWeChatDao.updateAuthAgain(weChatOfficialAuthInfoPO);
            iPropertyWeChatDao.deleteNeedlessData(weChatOfficialAuthInfoPO);
            return 1;
        }*/
        // 处理初次授权和再次授权的逻辑优化，直接将原来的数据解绑，并添加数据
        // 先将数据解绑
        PropertyWeChatDTO propertyWeChatDTO = new PropertyWeChatDTO();
        propertyWeChatDTO.setLoginUserId(weChatOfficialAuthInfoPO.getPropertyUserId());
        propertyWeChatDTO.setAppId(weChatOfficialAuthInfoPO.getAppId());
        int res = iPropertyWeChatDao.deleteAppIdBinding(propertyWeChatDTO);
        // 添加新数据
        weChatOfficialAuthInfoPO.setInfoId(LogicIdUtil.bussinessId());
        weChatOfficialAuthInfoPO.setAuthStatus(1);
        weChatOfficialAuthInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
        weChatOfficialAuthInfoPO.setCreateTime(new Date());
        weChatOfficialAuthInfoPO.setUpdateTime(weChatOfficialAuthInfoPO.getCreateTime());
        Map<String,Object> map = SqlUtil.durableData(weChatOfficialAuthInfoPO,PlatformConstants.TABLE_SAVE);
        res += iPropertyWeChatDao.save(map);
        return res;
    }

    /**
     * <desc>
     *      查询开通微信支付的所有项目及详细信息
     * </desc>
     *
     * @return 开通微信支付的所有项目及详细信息
     * @author wangzhi
     * @createDate 2019/10/23
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<OperateWeChatVO> getWeChatPayPage(OperateWeChatDTO operateWeChatDTO) throws Exception {
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(operateWeChatDTO);
        Page<OperateWeChatVO> page = new Page<>();
        page.getPage().setPageSize(operateWeChatDTO.getPageSize());
        page.getPage().setCurrentPage(operateWeChatDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<OperateWeChatVO> operateWeChatVOS = iPropertyWeChatDao.getWeChatPayPage(params);
        page.setRows(operateWeChatVOS, iPropertyWeChatDao.getWeChatPayPageRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      添加公众号AppSecret
     * </desc>
     *
     * @return 受影响行数
     * @author wangzhi
     * @createDate 2019/11/05
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveAppSecret(PropertyWeChatDTO propertyWeChatDTO) throws Exception {
        return iPropertyWeChatDao.updateAppSecret(propertyWeChatDTO);
    }
}
